<template>
    <div style="padding: 20px">
      <el-form v-if="joinFrom" :model="rtcForm" ref="rtcForm" label-width="80px" style="width: 50%;padding: 20px">
        <el-form-item label="昵称" prop="displayName">
          <el-input placeholder="请输入昵称" v-model="rtcForm.displayName"></el-input>
        </el-form-item>
        <el-form-item label="频道" prop="channelId">
          <el-input placeholder="请输入频道号" v-model="rtcForm.channelId"></el-input>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" @click="joinChannel(aliWebrtc,rtcForm.displayName)">加入视频</el-button>
        </div>
      </el-form>
      <div v-else>
        <div style="margin: 10px">
          <el-button size="small" type="danger"  @click="endVideo(aliWebrtc)">挂断</el-button>
        </div>
        <el-row :gutter="20" style="text-align: center">
            <el-col :span="6">
                <!--本机频道-->
                <video ref="localVideo" autoplay playsinline width="100%" height="230px"></video>
                <span>本机通道</span>
            </el-col>
            <el-col :span="6" v-for="(item,index) in videoList" :key="index" >
                <video ref="remoteVideo" autoplay playsinline width="100%" height="230px"></video>
                <span>通道{{index}}</span>
            </el-col>
        </el-row>
      </div>
    </div>
</template>

<script>
import 'aliyun-webrtc-sdk'
import {joinChannel} from "@/api/alirtc";
export default {
    name: "index",
    data(){
        return{
          aliWebrtc:null,
           rtcForm:{
             displayName:"",
             channelId:""
           },
          joinFrom:true,
          videoList:[]
        }
    },
    created() {
        this.aliWebrtc = new AliRtcEngine();
        this.isSupport(this.aliWebrtc,true)
    },

    methods:{
        //校验当前设备是否支持
        isSupport(val,debug){
            let option = {}
            if (debug){
                option.isDebug=true
            }
            val.isSupport(option).then((res)=>{
                this.onJoinEvent(val)
                this.onPublisher(val)
                this.onBye(val)
                this.onLeave(val)
                this.OnRefresh(val)
            }).catch((error)=>{
                console.log("不支持webrtc",error.message)
            })
        },

        //本地预览
        startPreview(val){
          this.aliWebrtc.startPreview(this.$refs.localVideo).then(()=>{
                console.log("本地预览")
            }).catch((error) => {
                console.log("预览失败",error)
            });
        },

        //获取设备的信息数据
        getDevices(val){
            val.getDevices().then((res)=>{
                console.log("获取设备的信息数据",res)
            }).catch((error)=>{
                console.log("获取设备的信息数据失败",error.message)
            });
        },


        //加入频道
        joinChannel(val,displayName){
          joinChannel(this.rtcForm).then(res=>{
            val.joinChannel(res.data,displayName).then(obj=>{
              this.joinFrom=false;
              this.$nextTick(() => {
                this.startPreview(val)
                this.publish(val)
              });
              console.log("加入频道成功")
            }).catch((error)=>{
              console.log("加入频道失败",error)
            })
          }).catch(error=>{
            console.log("加入频道失败",error)
          })
        },

        //推发布流
      publish(val){
          val.configLocalAudioPublish = true;
          val.configLocalCameraPublish = true;
          val.publish().then(()=>{
            console.log("发布流成功")
          } ,(error)=>{
            console.log(error.message);
          });
      },

      // remote用户加入房间 onJoin
      onJoinEvent(val){
        val.on("onJoin", (publisher) => {
          if(publisher.userId){
              console.log(publisher.userId)
          }
          //重置订阅状态
          //默认订阅远端音频和视频大流，但需要调用subscribe才能生效
          //这里取消默认订阅，根据需求进行订阅
          val.configRemoteAudio(publisher.userId, true);
          val.configRemoteCameraTrack(publisher.userId, true, true);
          // showAlert(publisher.displayName + "加入房间","success");
          console.log(publisher.displayName + "加入房间");
        });
      },
      //remote流发布事件 onPublish
      onPublisher(val){
        val.on("onPublisher", (publisher) => {
          val.subscribe(publisher.userId).then((userId)=>{
            console.log(userId)
            this.videoList.push(publisher)
            this.$nextTick(() => {
                console.log(this.$refs.remoteVideo[this.videoList.length-1])
                val.setDisplayRemoteVideo(userId,this.$refs.remoteVideo[this.videoList.length-1],1)
            });
          },(error)=>{
            console.log(error.message);
          });
        });
      },
      //remote流结束发布事件 onUnPublisher
      onUnPublisher(val){
        val.on("onUnPublisher", (publisher) => {
          console.log("onUnPublisher",publisher);
        });
      },
      // 被服务器踢出或者频道关闭时回调 onBye
      onBye(val){
        val.on("onBye",(message) =>{
          //1:被服务器踢出
          //2:频道关闭
          //3:同一个ID在其他端登录,被服务器踢出
          var msg;
          switch (message.code) {
            case 1: msg = "被服务器踢出";
              break;
            case 2: msg = "频道关闭";
              break;
            case 3: msg = "同一个ID在其他端登录,被服务器踢出";
              break;
            default: msg = "onBye";
          }

        });
      },
      /**
       * 检测到用户离开频道
       * 更新用户列表
       * 移除用户视图
       */
      onLeave(val){
        val.on("onLeave", (publisher) => {
          console.log(publisher);
          this.videoList.splice(this.videoList.findIndex(function(item) {
              return item === publisher;
          }),1)
        })
      },
      //页面刷新时调用
      OnRefresh(val){
        window.onbeforeunload=function (e) {
          if (!val){
            console.log("isSupport失败");
            return ;
          }
          val.leaveChannel();
          val.dispose();
        }
      },
      //移除 dom
      endVideo(val){
        if (val!=null){
          val.leaveChannel();
          val.dispose();
        }
        this.joinFrom=true;
      }




    }
}
</script>

<style scoped>

</style>